<%-- 
    Document   : SendMessage
    Created on : Dec 7, 2011, 2:39:31 AM
    Author     : hendrikde
--%>

<%@page import="java.util.Calendar"%>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<% if(session.getAttribute("LoggedIn")==null)
       {
    response.sendRedirect("index.html");
    return;
        }

%>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>Send a New Message</title>
    </head>
    <body>
        <%
        int recipient = Integer.parseInt(request.getParameter("recipient"));
        String subject = request.getParameter("subject");
        String content = request.getParameter("content");
        int sender = Integer.parseInt(session.getAttribute("UserID").toString());
        
        DBClasses.GetConnection gc = new DBClasses.GetConnection();
        java.sql.Connection conn = gc.getConnection();
        
        try {
            java.sql.Statement stmt1 = conn.createStatement();
            String query1 = "SELECT MAX(MessageID)"
                    + "FROM MESSAGES M";
            java.sql.ResultSet rs = stmt1.executeQuery(query1);
            int highestMessage = 0;
            while(rs.next())
                highestMessage= Integer.parseInt(rs.getString(1));
            highestMessage++;
            
            String query2 = "INSERT INTO Messages (MessageID, Date, Subject, Content, Sender, Receiver, MessageRead) " 
                    + "VALUES (?, ?, ?, ?, ?, ?, ?)";
            java.sql.PreparedStatement ps = conn.prepareStatement(query2);
            ps.setInt(1, highestMessage);
            ps.setDate(2, new java.sql.Date(System.currentTimeMillis()), Calendar.getInstance());
            ps.setString(3, subject);
            ps.setString(4, content);
            ps.setInt(5, sender);
            ps.setInt(6, recipient);
            ps.setInt(7, 0);
            
            System.out.println(ps.toString());
            
            ps.execute();
            

        }
        catch(Exception e) {
            e.printStackTrace();
        }
        finally
    {
        try{
            conn.commit();
            conn.close();
            response.sendRedirect("MessageIndex.jsp");
        }
        catch(Exception ee)
                               {
                ee.printStackTrace();
            }
        }
        
        %>
    </body>
</html>
